package com.unlcn.ils.kas.service.order.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.unlcn.ils.kas.dao.model.order.*;
import com.unlcn.ils.kas.dao.model.order.bo.OrderLineBo;
import com.unlcn.ils.kas.service.map.BaiDuMap.util.BaiDuMapRouteUtil;
import com.unlcn.ils.kas.service.order.*;
import com.unlcn.ils.kas.service.util.ErpUrl;
import com.unlcn.ils.kas.service.util.HttpClientUtil;
import com.unlcn.ils.kas.service.util.enums.order.*;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by lenovo on 2018/4/12.
 */
@Service
public class OrderExceptionServiceImpl implements OrderExceptionService {

    private static final Logger LOGGER = LoggerFactory.getLogger(OrderExceptionServiceImpl.class);

    /**
     * 订单在途日志 service
     */
    @Autowired
    private OrderOtdLogService orderOtdLogService;

    /**
     * 订单在途日志明细 service
     */
    @Autowired
    private OrderOtdLogDetailService orderOtdLogDetailService;

    /**
     * 订单在途跟踪 service
     */
    @Autowired
    private OrderOtdService orderOtdService;

    /**
     * 订单在途跟踪明细 service
     */
    @Autowired
    private OrderOtdDetailService orderOtdDetailService;

    /**
     * 客户 service
     */
    @Autowired
    private CustomerService customerService;

    /**
     * 拉取订单异常 service
     */
    @Autowired
    private OrderOtdExceptionService orderOtdExceptionService;

    /**
     * erp 接口地址 model
     */
    @Autowired
    private ErpUrl erpUrl;

    @Override
    public List<Map<String, String>> pullOrder(String[] sysOrderNos) {

        // 结果信息
        List<Map<String, String>> result = new ArrayList<>();

        for (String sysOrderNo : sysOrderNos) {

            Map<String, String> resultMap = new HashMap<>();

            try {
                // 获取订单详情
                Map<String, String> orderDetailParams = new HashMap<>();
                orderDetailParams.put("vcdn", sysOrderNo);
                String getOrderDetailResult = HttpClientUtil.post(erpUrl.getGetErpOrderDetail(), orderDetailParams,
                        600000000);
                LOGGER.info("(" + sysOrderNo + ")获取订单详情接口返回信息: ", getOrderDetailResult);
                if (StringUtils.isEmpty(getOrderDetailResult)) {
                    resultMap.put("sysOrderNo", sysOrderNo);
                    resultMap.put("result", "请求订单详情接口异常，拉取失败");
                    result.add(resultMap);
                    continue;
                }

                JSONObject json = JSONObject.parseObject(getOrderDetailResult);
                Object obj = json.get("data");
                LOGGER.info("(" + sysOrderNo + ")" + "详情: ", obj);
                if (obj == null) {
                    resultMap.put("sysOrderNo", sysOrderNo);
                    resultMap.put("result", "无法找到订单详情，拉取失败");
                    result.add(resultMap);
                    continue;
                }
                OrderOtdLog orderOtdLog = analysisOrder((Map) obj);

                Map<String, String> onWayParams = new HashMap<>();
                onWayParams.put("vcdn", orderOtdLog.getSysOrderNo());
                String onWayResult = HttpClientUtil.post(erpUrl.getGetErpOnway(), onWayParams, 600000000);

                List<OrderOtdLogDetail> orderOtdLogDetailList = new ArrayList<>();
                if (!StringUtils.isEmpty(onWayResult)) {
                    // 将在途信息转换成map集合
                    List<Map> onWayList = getMap(onWayResult);

                    if (!CollectionUtils.isEmpty(onWayList)) {
                        for (Map onWayMap : onWayList) {
                            OrderOtdLogDetail orderOtdLogDetail = analysisOnWayInfo(onWayMap);
                            orderOtdLogDetailList.add(orderOtdLogDetail);
                        }
                    }
                }

                // 保存订单详细信息、在途信息
                saveOrderInfo(orderOtdLog, orderOtdLogDetailList);

                resultMap.put("sysOrderNo", sysOrderNo);
                resultMap.put("result", "成功拉取");
            } catch (Exception e) {
                LOGGER.error("拉取订单" + sysOrderNo + "发生异常", e);

                resultMap.put("sysOrderNo", sysOrderNo);
                resultMap.put("result", "拉取失败");
                resultMap.put("msg", JSON.toJSONString(e));

                continue;
            } finally {
                result.add(resultMap);
            }
        }

        return result;
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public void saveOrderInfo(OrderOtdLog orderOtdLog, List<OrderOtdLogDetail> orderOtdLogDetailList) {

        // 保存在途跟踪日志表
        orderOtdLog.setGmtCreate(new Date());
        orderOtdLogService.insert(orderOtdLog);
        // 保存在途跟踪日志明细信息
        for (int i = 0; orderOtdLogDetailList.size() > i; i++) {
            orderOtdLogDetailList.get(i).setHeadId(orderOtdLog.getId());
        }
        if (!CollectionUtils.isEmpty(orderOtdLogDetailList)) {
            orderOtdLogDetailService.batchInsert(orderOtdLogDetailList);
        }

        // 校验订单是否已经存在 kas 订单跟踪表
        EntityWrapper<OrderOtd> ew = new EntityWrapper<>();
        ew.eq("sys_order_no", orderOtdLog.getSysOrderNo());
        List<OrderOtd> orderOtdList = orderOtdService.selectList(ew);

        // 转换跟踪订单
        OrderOtd orderOtd = null;
        if (orderOtdLog.getCustomerNo().equals(CustomNoEnum.GF.getValue())) {
            orderOtd = gfTransformation(orderOtdLog);
        } else if (orderOtdLog.getCustomerNo().equals(CustomNoEnum.KG.getValue())) {
            orderOtd = kgTransformation(orderOtdLog);
        }

        // 存在则更新，否则插入
        if (!CollectionUtils.isEmpty(orderOtdList)) {
            // 提车时间是否为空，为空时做更新，否则不修改
            if (orderOtdList.get(0).getPickTime() != null) {
                orderOtd.setPickTime(orderOtdList.get(0).getPickTime());
            }
            // 入中转库时间时间是否为空，为空时做更新，否则不修改
            if (orderOtdList.get(0).getInboundTime() != null) {
                orderOtd.setInboundTime(orderOtdList.get(0).getPickTime());
            }
            // 安排运力时间是否为空，为空时做更新，否则不修改
            if (orderOtdList.get(0).getArrangeCapacityTime() != null) {
                orderOtd.setArrangeCapacityTime(orderOtdList.get(0).getArrangeCapacityTime());
            }
            // 入铁路库时间是否为空，为空时做更新，否则不修改
            if (orderOtdList.get(0).getEnterRailwayTime() != null) {
                orderOtd.setEnterRailwayTime(orderOtdList.get(0).getEnterRailwayTime());
            }
            // 出中联库时间是否为空，为空时做更新，否则不修改
            if (orderOtdList.get(0).getOutboundTime() != null) {
                orderOtd.setOutboundTime(orderOtdList.get(0).getOutboundTime());
            }
            // 装车时间是否为空，为空时做更新，否则不修改
            if (orderOtdList.get(0).getLoadTime() != null) {
                orderOtd.setLoadTime(orderOtdList.get(0).getLoadTime());
            }
            // 离昌时间是否为空，为空时做更新，否则不修改
            if (orderOtdList.get(0).getLeaveTime() != null) {
                orderOtd.setLeaveTime(orderOtdList.get(0).getLeaveTime());
            }
            // 运抵时间是否为空，为空时做更新，否则不修改
            if (orderOtdList.get(0).getShiptoTime() != null) {
                orderOtd.setShiptoTime(orderOtdList.get(0).getShiptoTime());
            }
            // 发运类型是否为空，为空时做更新，否则不修改
            if (!StringUtils.isEmpty(orderOtdList.get(0).getShipmentType())) {
                orderOtd.setShipmentType(orderOtdList.get(0).getShipmentType());
            }
            // 打单时间是否为空，为空时做更新，否则不修改
            if (orderOtdList.get(0).getPrintOrderTime() != null) {
                orderOtd.setPrintOrderTime(orderOtdList.get(0).getPrintOrderTime());
            }
            // 回单时间是否为空，为空时做更新，否则不修改
            if (orderOtdList.get(0).getReturnOrderTime() != null) {
                orderOtd.setReturnOrderTime(orderOtdList.get(0).getReturnOrderTime());
            }

            // 更新在途跟踪表
            orderOtd.setId(orderOtdList.get(0).getId());
            orderOtd.setGmtCreate(orderOtdList.get(0).getGmtCreate());
            orderOtd.setGmtModified(new Date());
            orderOtdService.updateById(orderOtd);
            LOGGER.info("成功更新订单", orderOtd.getSysOrderNo());
        } else {
            // 保存在途跟踪表
            orderOtd.setGmtCreate(new Date());
            orderOtdService.insert(orderOtd);
            LOGGER.info("成功插入订单", orderOtd.getSysOrderNo());
        }

        // 如果订单在kas里已经存在 运抵时间||回单时间，则不更新
        if (orderOtd.getShiptoTime() != null || orderOtd.getReturnOrderTime() != null) {
            return;
        }

        LOGGER.info(orderOtdLogDetailList.size() + "条在途信息");

        // 保存在途跟踪明细信息
        List<OrderOtdDetail> orderOtdDetailList = new ArrayList<>();
        for (OrderOtdLogDetail orderOtdLogDetail : orderOtdLogDetailList) {
            OrderOtdDetail orderOtdDetail = new OrderOtdDetail();
            BeanUtils.copyProperties(orderOtdLogDetail, orderOtdDetail);

            // 计算运输距离
            String startAddress = orderOtdDetail.getProvince() + orderOtdDetail.getCity() + orderOtdDetail.getArea()
                    + orderOtdDetail.getAddress();
            String endAddress = orderOtdLog.getdProvince() + orderOtdLog.getdCity() + orderOtdLog.getdAddress();
            BaiDuMapRouteUtil baiDuMapRouteUtil = new BaiDuMapRouteUtil();
            Number distance = baiDuMapRouteUtil.getDistance(startAddress, endAddress) / 1000;
            orderOtdDetail.setDistance(distance.floatValue());

            orderOtdDetailList.add(orderOtdDetail);
        }
        if (!CollectionUtils.isEmpty(orderOtdDetailList)) {
            orderOtdDetailService.batchInsert(orderOtdDetailList);
            LOGGER.info("成功更新在途信息", orderOtdLog.getSysOrderNo());
        }
    }

    @Override
    public Page<OrderLineBo> exceptionLine(Page<OrderOtd> page) {
        EntityWrapper<OrderOtd> ew = new EntityWrapper<>();
        // 查询条件
        if (!StringUtils.isEmpty(page.getCondition())) {
            // 客户编号
            if (!StringUtils.isEmpty(page.getCondition().get("customerNo"))) {
                ew.eq("koo.customer_no", page.getCondition().get("customerNo").toString());
            }
            // 异常分类
            if (!StringUtils.isEmpty(page.getCondition().get("classCode"))) {
                Integer classCode = Integer.valueOf(page.getCondition().get("classCode").toString());
                if (classCode == OrderExceptionClassEnum.CLASS_ONE.getCode()) {
                    ew.addFilter(" (koo.driver_phone is NULL OR koo.driver_phone='') ");
                } else if (classCode == OrderExceptionClassEnum.CLASS_TWO.getCode()) {
                    String format = "yyyy-MM-dd HH:mm:ss";
                    DateTime dt = new DateTime();
                    Integer year = dt.getYear();
                    Integer month = dt.getMonthOfYear();
                    int day = dt.getDayOfMonth();
                    DateTime todayDateTime = new DateTime(year, month, day, 0, 0, 0);

                    DateTime yesterdayStartDateTime = todayDateTime.minusDays(1);
                    DateTime yesterdayEndDateTime = todayDateTime;

                    DateTime beforeYesterdayStartDateTime = todayDateTime.minusDays(2);
                    DateTime beforeYesterdayEndDateTime = todayDateTime.minusDays(1);

                    String yesterdayStartDate = yesterdayStartDateTime.toString(format);
                    String yesterdayEndDate = yesterdayEndDateTime.toString(format);

                    String beforeYesterdayStartDate = beforeYesterdayStartDateTime.toString(format);
                    String beforeYesterdayEndDate = beforeYesterdayEndDateTime.toString(format);

                    String whereSql = "(" + "(\n" + "\t\t\tSELECT\n" + "\t\t\t\tkood1.address\n" + "\t\t\tFROM\n"
                            + "\t\t\t\tkas_order_otd_detail kood1\n" + "\t\t\tWHERE\n"
                            + "\t\t\t\tkood1.sys_order_no = koo.sys_order_no\n" + "\t\t\tAND kood1.track_time BETWEEN '"
                            + yesterdayStartDate + "'\n" + "\t\t\tAND '" + yesterdayEndDate + "'\n" + "\t\t\tORDER BY\n"
                            + "\t\t\t\tkood1.track_time DESC\n" + "\t\t\tLIMIT 0,\n" + "\t\t\t1\n" + "\t\t) = (\n"
                            + "\t\t\tSELECT\n" + "\t\t\t\tkood2.address\n" + "\t\t\tFROM\n"
                            + "\t\t\t\tkas_order_otd_detail kood2\n" + "\t\t\tWHERE\n"
                            + "\t\t\t\tkood2.sys_order_no = koo.sys_order_no\n" + "\t\t\tAND kood2.track_time BETWEEN '"
                            + beforeYesterdayStartDate + "'\n" + "\t\t\tAND '" + beforeYesterdayEndDate + "'\n"
                            + "\t\t\tORDER BY\n" + "\t\t\t\tkood2.track_time DESC\n" + "\t\t\tLIMIT 0,\n" + "\t\t\t1\n"
                            + "\t\t)\n" + "\t\tOR (\n" + "\t\t\t! EXISTS (\n" + "\t\t\t\tSELECT\n"
                            + "\t\t\t\t\tkood3.id\n" + "\t\t\t\tFROM\n" + "\t\t\t\t\tkas_order_otd_detail kood3\n"
                            + "\t\t\t\tWHERE\n" + "\t\t\t\t\tkood3.sys_order_no = koo.sys_order_no\n"
                            + "\t\t\t\tAND kood3.track_time BETWEEN '" + yesterdayStartDate + "'\n" + "\t\t\t\tAND '"
                            + yesterdayEndDate + "'\n" + "\t\t\t)\n" + "\t\t\tOR ! EXISTS (\n" + "\t\t\t\tSELECT\n"
                            + "\t\t\t\t\tkood4.id\n" + "\t\t\t\tFROM\n" + "\t\t\t\t\tkas_order_otd_detail kood4\n"
                            + "\t\t\t\tWHERE\n" + "\t\t\t\t\tkood4.sys_order_no = koo.sys_order_no\n"
                            + "\t\t\t\tAND kood4.track_time BETWEEN '" + beforeYesterdayStartDate + "'\n"
                            + "\t\t\t\tAND '" + beforeYesterdayEndDate + "'\n" + "\t\t\t)\n" + "\t\t)\n" + "\t)\n"
                            + " and koo.transport_type<>'自提' and koo.pick_time>'2019-4-1' "
                            + " AND koo.leave_time IS NOT NULL\n" + "AND koo.shipto_time IS NULL";

                    ew.addFilter(whereSql);
                } else if (classCode == OrderExceptionClassEnum.CLASS_THREE.getCode()) {
                    ew.addFilter(" (koo.driver_phone is not NULL AND koo.driver_phone!='') AND substring("
                            + "koo.driver_phone," + "LOCATE('-', koo.driver_phone)," + "4"
                            + ") NOT IN ('130','131','132','155','156','186','185','145','134','135','136','137','138','139','150','151','152','157','158','159','182','183','188','187','133','153','180','181','189') "
                            + " AND (LENGTH(koo.driver_phone)-LOCATE('-', koo.driver_phone))=11");
                } else if (classCode == OrderExceptionClassEnum.CLASS_FOUR.getCode()) {
                    ew.addFilter(" koo.leave_time>=koo.shipto_time ");
                } else if (classCode == OrderExceptionClassEnum.CLASS_FIVE.getCode()) {
                    ew.addFilter(" koo.shipto_time>=koo.returnOrder_time ");
                } else if (classCode == OrderExceptionClassEnum.CLASS_SIX.getCode()) {
                    String whereSql = " koo.transport_type<>'自提' and koo.pick_time>'2019-4-1' "
                            + " AND koo.leave_time IS NOT NULL AND koo.shipto_time IS NULL"
                            + " and not exists(select 1 from kas_order_otd_detail od where od.sys_order_no=koo.sys_order_no )";
                    ew.addFilter(whereSql);
                } else if (classCode == OrderExceptionClassEnum.CLASS_SEVEN.getCode()) {
                    String whereSql = " koo.transport_type<>'自提' and koo.pick_time>'2019-4-1' "
                            + " AND koo.leave_time IS NOT NULL AND koo.shipto_time IS NULL"
                            + " and not exists(select 1 from kas_order_otd_detail od where od.sys_order_no=koo.sys_order_no and od.track_time>=date_sub(current_date(),interval 2 DAY))";
                    ew.addFilter(whereSql);
                }
            }
        }

        List<OrderOtd> orderOtdList = orderOtdService.exceptionLine(page, ew);
        page.setRecords(orderOtdList);

        Page<OrderLineBo> returnPage = new Page<>();
        BeanUtils.copyProperties(page, returnPage);

        List<OrderLineBo> orderLineBoList = new ArrayList<>();
        for (OrderOtd orderOtd : orderOtdList) {
            OrderLineBo orderLineBo = new OrderLineBo();
            BeanUtils.copyProperties(orderOtd, orderLineBo);

            // 查询记录数
            Wrapper<OrderOtdDetail> detailEntity = new EntityWrapper<>();
            detailEntity.eq("sys_order_no", orderOtd.getSysOrderNo());
            detailEntity.eq("isdelete", OrderDetailDeleteFlagEnum.NORMAL.getCode());
            Integer recordCount = orderOtdDetailService.selectCount(detailEntity);
            orderLineBo.setRecordCount(recordCount);

            orderLineBoList.add(orderLineBo);
        }
        returnPage.setRecords(orderLineBoList);

        return returnPage;
    }

    private OrderOtd kgTransformation(OrderOtdLog orderOtdLog) {

        OrderOtd orderOtd = new OrderOtd();

        BeanUtils.copyProperties(orderOtdLog, orderOtd);

        // 判断订单状态
        if (orderOtd.getLeaveTime() == null) {
            orderOtd.setOrderStatus("未离昌");
        } else {
            if (orderOtd.getShiptoTime() == null) {
                orderOtd.setOrderStatus("在途");
            } else {
                orderOtd.setOrderStatus("交付");
            }
        }

        // 查询客户编号
        EntityWrapper<Customer> customerEntity = new EntityWrapper<>();
        customerEntity.eq("name", orderOtd.getCustomerName());
        List<Customer> customerList = customerService.selectList(customerEntity);
        if (!CollectionUtils.isEmpty(customerList)) {
            orderOtd.setCustomerNo(customerList.get(0).getCode());
        }

        // 数据源
        orderOtd.setWay(OrderWayEnum.WAY_SYS_INTF.getCode());

        return orderOtd;
    }

    private OrderOtd gfTransformation(OrderOtdLog orderOtdLog) {

        OrderOtd orderOtd = new OrderOtd();

        BeanUtils.copyProperties(orderOtdLog, orderOtd);

        // 计算运输距离
        String startAddress = orderOtd.getoProvince() + orderOtd.getoCity() + orderOtd.getoAddress();
        String endAddress = orderOtd.getdProvince() + orderOtd.getdCity() + orderOtd.getdAddress();
        BaiDuMapRouteUtil baiDuMapRouteUtil = new BaiDuMapRouteUtil();
        Number distance = baiDuMapRouteUtil.getDistance(startAddress, endAddress) / 1000;
        orderOtd.setDistance(distance.floatValue());

        // 判断订单状态
        if (orderOtd.getLeaveTime() == null) {
            orderOtd.setOrderStatus("未离昌");
        } else {
            if (orderOtd.getShiptoTime() == null) {
                orderOtd.setOrderStatus("在途");
            } else {
                orderOtd.setOrderStatus("交付");
            }
        }

        // 查询客户编号
        EntityWrapper<Customer> customerEntity = new EntityWrapper<>();
        customerEntity.eq("name", orderOtd.getCustomerName());
        List<Customer> customerList = customerService.selectList(customerEntity);
        if (!CollectionUtils.isEmpty(customerList)) {
            orderOtd.setCustomerNo(customerList.get(0).getCode());
        }

        // 数据源
        orderOtd.setWay(OrderWayEnum.WAY_SYS_INTF.getCode());

        // 计算预计送达时间
        orderOtd.setPlanShiptoTime(this.expectedArrivalTime(orderOtd));

        return orderOtd;
    }

    /**
     * 计算预计送达时间
     * 
     * @param orderOtd
     * @return
     */
    public Date expectedArrivalTime(OrderOtd orderOtd) {

        if (orderOtd == null)
            return null;

        // 离昌前
        if (orderOtd.getLeaveTime() == null) {
            // 未安排运力，预计送达时间为空
            if (orderOtd.getArrangeCapacityTime() == null) {
                return null;
            } else {
                // 已安排运力，预计送达时间=安排时间+在途时效+流转时间
                BaiDuMapRouteUtil baiDuMapRouteUtil = new BaiDuMapRouteUtil();
                String startAddress = orderOtd.getoProvince() + orderOtd.getoCity() + orderOtd.getoAddress();
                String endAddress = orderOtd.getdProvince() + orderOtd.getdCity() + orderOtd.getdAddress();
                double distance = baiDuMapRouteUtil.getDistance(startAddress, endAddress);
                distance = distance / 1000;
                Double timeLimitation = 0.00;
                Double circulationTime = 0.00;
                if (orderOtd.getTransportType().contains("零公里")) {
                    // 零公里在途时效
                    timeLimitation = distance / 550;
                    // 零公里流转时间
                    circulationTime = 1.0;
                } else if (orderOtd.getTransportType().contains("三位板") || orderOtd.getTransportType().contains("四位板")) {
                    // 人送在途时效
                    timeLimitation = distance / 550;
                    // 三位板流转时间
                    circulationTime = 0.0;
                } else if (orderOtd.getTransportType().contains("人送")) {
                    // 人送在途时效
                    timeLimitation = distance / 550;
                    // 人送流转时间
                    circulationTime = 0.5;
                } else if (orderOtd.getTransportType().contains("铁运")) {
                    // 铁运在途时效
                    timeLimitation = distance / 250;
                    // 铁运流转时间
                    circulationTime = 2.0;
                } else if (orderOtd.getTransportType().contains("水运")) {
                    // 水运在途时效
                    timeLimitation = distance / 185;
                    // 水运流转时间
                    circulationTime = 2.0;
                }

                Calendar calendar = Calendar.getInstance();
                // 安排运力时间
                calendar.setTime(orderOtd.getArrangeCapacityTime());
                Math.ceil(timeLimitation);
                // 加上在途时效
                Number limitation = Math.ceil(timeLimitation) * 24;
                calendar.add(Calendar.HOUR_OF_DAY, limitation.intValue());
                // 加上流转时间
                Number circulation = circulationTime * 24;
                calendar.add(Calendar.HOUR_OF_DAY, circulation.intValue());

                return calendar.getTime();
            }
        }
        // 离昌后
        else {
            // 计算剩余公里数
            BaiDuMapRouteUtil baiDuMapRouteUtil = new BaiDuMapRouteUtil();
            String startAddress = orderOtd.getoProvince() + orderOtd.getoCity() + orderOtd.getoAddress();
            String endAddress = orderOtd.getdProvince() + orderOtd.getdCity() + orderOtd.getoAddress();
            double distance = baiDuMapRouteUtil.getDistance(startAddress, endAddress);
            distance = distance / 1000;
            Number limitation = null;
            // 加上时效，算出预计送达时间
            if (orderOtd.getTransportType().contains("零公里") || orderOtd.getTransportType().contains("三位板")
                    || orderOtd.getTransportType().contains("四位板")) {
                limitation = Math.ceil(distance / 550) * 24;
            } else if (orderOtd.getTransportType().contains("人送")) {
                limitation = Math.ceil(distance / 550) * 24;
            } else if (orderOtd.getTransportType().contains("铁运")) {
                limitation = Math.ceil(distance / 250) * 24 + (24) * 3;
            } else if (orderOtd.getTransportType().contains("水运")) {
                limitation = Math.ceil(distance / 185) * 24 + (24) * 3;
            }
            Calendar calendar = Calendar.getInstance();
            if (orderOtd.getNewestTime() == null)
                return null;
            calendar.setTime(orderOtd.getNewestTime());
            calendar.add(Calendar.HOUR_OF_DAY, limitation.intValue());

            return calendar.getTime();
        }
    }

    /**
     * 将ResponseEntity结果转换成map集合
     * 
     * @param result
     * @return
     */
    private List<Map> getMap(String result) {

        JSONObject json = JSONObject.parseObject(result);

        if (json == null || json.get("data") == null)
            return null;

        JSONArray jsonArray = JSONArray.parseArray(json.get("data").toString());

        if (jsonArray == null || jsonArray.size() == 0)
            return null;

        // 遍历订单JSON串，一一转换成map
        List<Map> dataMapList = new ArrayList<Map>();
        for (Object obj : jsonArray) {
            Map map = (Map) obj;
            dataMapList.add(map);
        }

        return dataMapList;
    }

    /**
     * 格式化订单
     * 
     * @param map
     * @return
     */
    private OrderOtdLog analysisOrder(Map map) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        OrderOtdLog orderOtdLog = new OrderOtdLog();
        if (map == null)
            return orderOtdLog;

        try {
            // 离昌时间
            if (!StringUtils.isEmpty(map.get("dtonway"))) {
                orderOtdLog.setLeaveTime(simpleDateFormat.parse(map.get("dtonway").toString()));
            }
            // 安排运力时间
            if (!StringUtils.isEmpty(map.get("dtassign"))) {
                orderOtdLog.setArrangeCapacityTime(simpleDateFormat.parse(map.get("dtassign").toString()));
            }
            // 入铁路库时间
            if (!StringUtils.isEmpty(map.get("dt2rail"))) {
                orderOtdLog.setEnterRailwayTime(simpleDateFormat.parse(map.get("dt2rail").toString()));
            }
            // 入中转库时间
            if (!StringUtils.isEmpty(map.get("dtcache"))) {
                orderOtdLog.setInboundTime(simpleDateFormat.parse(map.get("dtcache").toString()));
            }
            // 订单创建时间
            if (!StringUtils.isEmpty(map.get("dtcreate"))) {
                orderOtdLog.setOrderCreateTime(simpleDateFormat.parse(map.get("dtcreate").toString()));
            }
            // 运抵时间
            if (!StringUtils.isEmpty(map.get("dtdelivery"))) {
                orderOtdLog.setShiptoTime(simpleDateFormat.parse(map.get("dtdelivery").toString()));
            }
            // 最新在途时间
            if (!StringUtils.isEmpty(map.get("dtlocation"))) {
                orderOtdLog.setNewestTime(simpleDateFormat.parse(map.get("dtlocation").toString()));
            }
            // 订单日期
            if (!StringUtils.isEmpty(map.get("dtorder"))) {
                orderOtdLog.setOrderDate(simpleDateFormat.parse(map.get("dtorder").toString()));
            }
            // 出中联库时间
            if (!StringUtils.isEmpty(map.get("dtout_3pl"))) {
                orderOtdLog.setOutboundTime(simpleDateFormat.parse(map.get("dtout_3pl").toString()));
            }
            // 提车时间
            if (!StringUtils.isEmpty(map.get("dtout_factory"))) {
                orderOtdLog.setPickTime(simpleDateFormat.parse(map.get("dtout_factory").toString()));
            }
            // 装车时间
            if (!StringUtils.isEmpty(map.get("dtload"))) {
                orderOtdLog.setLoadTime(simpleDateFormat.parse(map.get("dtload").toString()));
            }
            // 客户编号
            if (!StringUtils.isEmpty(map.get("icustomerid"))) {
                orderOtdLog.setCustomerNo(map.get("icustomerid").toString());
            }
            // 收车地址
            if (!StringUtils.isEmpty(map.get("vcaddress_dest"))) {
                orderOtdLog.setdAddress(map.get("vcaddress_dest").toString());
            }
            // 发车地址
            if (!StringUtils.isEmpty(map.get("vcaddress_origin"))) {
                orderOtdLog.setoAddress(map.get("vcaddress_origin").toString());
            }
            // 收车城市
            if (!StringUtils.isEmpty(map.get("vccity_dest"))) {
                orderOtdLog.setdCity(map.get("vccity_dest").toString());
            }
            // 发车城市
            if (!StringUtils.isEmpty(map.get("vccity_origin"))) {
                orderOtdLog.setoCity(map.get("vccity_origin").toString());
            }
            // 客户名称
            if (!StringUtils.isEmpty(map.get("vccustomer"))) {
                orderOtdLog.setCustomerName(map.get("vccustomer").toString());
            }
            // 经销商名称
            if (!StringUtils.isEmpty(map.get("vcdealername"))) {
                orderOtdLog.setDealerName(map.get("vcdealername").toString());
            }
            // 经销商编号
            if (!StringUtils.isEmpty(map.get("vcdealerno"))) {
                orderOtdLog.setDealerNo(map.get("vcdealerno").toString());
            }
            // 客户订单号
            if (!StringUtils.isEmpty(map.get("vcdmsorderno"))) {
                orderOtdLog.setCustomerOrderNo(map.get("vcdmsorderno").toString());
            }
            // 系统订单号
            if (!StringUtils.isEmpty(map.get("vcdn"))) {
                orderOtdLog.setSysOrderNo(map.get("vcdn").toString());
            }
            // 系统订单号
            if (!StringUtils.isEmpty(map.get("vcdn"))) {
                orderOtdLog.setSysOrderNo(map.get("vcdn").toString());
            }
            // 司机联系方式
            if (!StringUtils.isEmpty(map.get("vcdriver"))) {
                orderOtdLog.setDriverPhone(map.get("vcdriver").toString());
            }
            // 车牌号
            if (!StringUtils.isEmpty(map.get("vclicense"))) {
                orderOtdLog.setLicensePlate(map.get("vclicense").toString());
            }
            // 最新在途位置
            if (!StringUtils.isEmpty(map.get("vclocation"))) {
                orderOtdLog.setNewestPosition(map.get("vclocation").toString());
            }
            // 备注
            if (!StringUtils.isEmpty(map.get("vcmemo"))) {
                orderOtdLog.setRemark(map.get("vcmemo").toString());
            }
            // 收车省
            if (!StringUtils.isEmpty(map.get("vcprovince_dest"))) {
                orderOtdLog.setdProvince(map.get("vcprovince_dest").toString());
            }
            // 发车省
            if (!StringUtils.isEmpty(map.get("vcprovince_origin"))) {
                orderOtdLog.setoProvince(map.get("vcprovince_origin").toString());
            }
            // 车型名称
            if (!StringUtils.isEmpty(map.get("vcstylename"))) {
                orderOtdLog.setStyleName(map.get("vcstylename").toString());
            }
            // 车型编码
            if (!StringUtils.isEmpty(map.get("vcstyleno"))) {
                orderOtdLog.setStyleCode(map.get("vcstyleno").toString());
            }
            // 运输方式
            if (!StringUtils.isEmpty(map.get("vctransmode"))) {
                orderOtdLog.setTransportType(map.get("vctransmode").toString());
            }
            // 发运类型
            if (!StringUtils.isEmpty(map.get("vctype"))) {
                orderOtdLog.setShipmentType(map.get("vctype").toString());
            }
            // 车架号
            if (!StringUtils.isEmpty(map.get("vcvin"))) {
                orderOtdLog.setVin(map.get("vcvin").toString());
            }
            // 打单时间
            if (!StringUtils.isEmpty(map.get("dtprint"))) {
                orderOtdLog.setPrintOrderTime(simpleDateFormat.parse(map.get("dtprint").toString()));
            }
            // 回单时间
            if (!StringUtils.isEmpty(map.get("dtreturn"))) {
                orderOtdLog.setReturnOrderTime(simpleDateFormat.parse(map.get("dtreturn").toString()));
            }
        } catch (Exception e) {
            LOGGER.error("OrderScheduled.analysisOrder ERROR: ", e);
        }

        return orderOtdLog;
    }

    /**
     * 格式化在途信息
     * 
     * @param map
     * @return
     */
    private OrderOtdLogDetail analysisOnWayInfo(Map map) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        OrderOtdLogDetail orderOtdLogDetail = new OrderOtdLogDetail();
        if (map == null)
            return orderOtdLogDetail;

        try {
            // 在途时间
            if (!StringUtils.isEmpty(map.get("dtlocation"))) {
                orderOtdLogDetail.setTrackTime(simpleDateFormat.parse(map.get("dtlocation").toString()));
            }
            // 所在省
            if (!StringUtils.isEmpty(map.get("vcprovince"))) {
                orderOtdLogDetail.setProvince(map.get("vcprovince").toString());
            }
            // 所在市
            if (!StringUtils.isEmpty(map.get("vccity"))) {
                orderOtdLogDetail.setCity(map.get("vccity").toString());
            }
            // 所在区/县
            if (!StringUtils.isEmpty(map.get("vcarea"))) {
                orderOtdLogDetail.setArea(map.get("vcarea").toString());
            }
            // 详细地址
            if (!StringUtils.isEmpty(map.get("vclocation"))) {
                orderOtdLogDetail.setAddress(map.get("vclocation").toString());
            }
            // 经度
            if (!StringUtils.isEmpty(map.get("vclongitude"))) {
                orderOtdLogDetail.setLongitude(new BigDecimal(map.get("vclongitude").toString()));
            }
            // 纬度
            if (!StringUtils.isEmpty(map.get("vclatitude"))) {
                orderOtdLogDetail.setLatitude(new BigDecimal(map.get("vclatitude").toString()));
            }
            // 系统订单号
            if (!StringUtils.isEmpty(map.get("vcdn"))) {
                orderOtdLogDetail.setSysOrderNo(map.get("vcdn").toString());
            }
        } catch (Exception e) {
            LOGGER.error("OrderScheduled.analysisOnWayInfo ERROR: ", e);
        }

        return orderOtdLogDetail;
    }
}
